package com.servlets;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.naming.NamingException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.MessageService;
import com.domain.Message;


public class DisplayMessagesServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	
	public DisplayMessagesServlet() {
		super();
	}

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ServletContext servletContext = this.getServletContext();
		WebApplicationContext webcontext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
		MessageService messageService = (MessageService) webcontext.getBean("messageService");

		List<Message> list = new ArrayList<Message>();
		try {
			list = messageService.getMessages();
		} catch (ClassNotFoundException | SQLException | NamingException e) {
			e.printStackTrace();
		}
		request.getSession().setAttribute("messages", list);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
